﻿using UnityEngine;

public class NotchSolution : MonoBehaviour
{
    public Camera UICamera;
    public float OffsetX = 0;

    bool liuHai = false;
    ScreenOrientation screenOrientationKind = ScreenOrientation.LandscapeLeft;
    Rect rect;
    float offsetRate = 0f;

    static bool extra = false;
    void Awake()
    {
        if (extra) Destroy(gameObject);
        else
        {
            extra = true;
            DontDestroyOnLoad(gameObject);
        }
    }

    private void Start()
    {
#if UNITY_ANDROID
        //AndroidJavaClass jc = new AndroidJavaClass("com.unity.androidplugin.ScreenAdaptation");
        //AndroidJavaClass jc_UnityDefault = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        //AndroidJavaObject jo_UnityActivity = jc_UnityDefault.GetStatic<AndroidJavaObject>("currentActivity");
        //jc.CallStatic("SetContext", jo_UnityActivity);
        //jc.CallStatic("StartScreenAdapation", "Unity Call");
#endif
        int dw = Screen.width - (int)Screen.safeArea.width;
        OnRec_LiuHaiInfo(dw + "|");
        //OnRec_LiuHaiInfo("100|20");
    }

    public void ScreenAdaptation(string size)
    {
        if(string.IsNullOrEmpty(size))
        {
            return;
        }

        OnRec_LiuHaiInfo(size);
    }

    private void OnRec_LiuHaiInfo(string size)
    {
        string[] scr = size.Split('|');
        int OffsetX = int.Parse(scr[0]);

        // yield return new WaitUntil(() => Use);

        // set the desired aspect ratio (the values in this example are
        // hard-coded for 16:9, but you could make them into public
        // variables instead so you can set them at design time)
        // float targetaspect = 16.0f / 9.0f;
        //float targetaspect = 128.0f / 72.0f;
        float targetaspect = (Screen.width - OffsetX) * 1.0f / (Screen.height * 1.0f);

        // determine the game window's current aspect ratio
        float windowaspect = (float)Screen.width / (float)Screen.height;

        // current viewport height should be scaled by this amount
        float scaleheight = windowaspect / targetaspect;

        // if scaled height is less than current height, add letterbox
        if (scaleheight < 1.0f)
        {
            Rect rect = UICamera.rect;

            rect.width = 1.0f;
            rect.height = scaleheight;
            rect.x = 0;
            rect.y = (1.0f - scaleheight) / 2.0f;

            //camera.rect = rect;
            UICamera.aspect /= scaleheight;
        }
        else // add pillarbox
        {
            float scalewidth = 1.0f / scaleheight;

            Rect rect = UICamera.rect;

            rect.width = scalewidth;
            rect.height = 1.0f;
            rect.x = (1.0f - scalewidth) / 2.0f;
            rect.y = 0;

            UICamera.aspect /= scalewidth;
        }
    }
}